﻿using MiniExcelLibs;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace GenUI.WPF.GenControls
{
    public class DataGridFile : Control
    {
        public Grid GridShow { get; private set; }
        public TreeView TvCsv { get; private set; }
        private Button Bt;
        private ICollection<Node> ListNode { get; set; } = new List<Node>();
        IEnumerable<string> txtPageSource { get; set; } = new List<string>();
        IEnumerable<string> txtPageSourceCopy { get; set; } = new List<string>();
        TxtPage TxtPage { get; set; } = new TxtPage();
        public string Title { get; set; } = "Title:";
        public string Pattern { get; set; } = ".csv|.xls|.xlsx|.txt";
        public string DirPath
        {
            get { return (string)GetValue(DirPathProperty); }
            set { SetValue(DirPathProperty, value); }
        }

        public static readonly DependencyProperty DirPathProperty =
            DependencyProperty.Register("DirPath", typeof(string), typeof(DataGridFile), new PropertyMetadata("", OnDirPathChanged));

        public string QueryStr
        {
            get { return (string)GetValue(QueryStrProperty); }
            set { SetValue(QueryStrProperty, value); }
        }

        // Using a DependencyProperty as the backing store for QueryStr.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty QueryStrProperty =
            DependencyProperty.Register("QueryStr", typeof(string), typeof(DataGridFile), new PropertyMetadata(""));


        public DataTable DtSelect { get; private set; } = null;

        static DataGridFile()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(DataGridFile), new FrameworkPropertyMetadata(typeof(DataGridFile)));
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            this.GridShow = GetTemplateChild("PART_Grid") as Grid;
            this.TvCsv = GetTemplateChild("PART_TV") as TreeView;
            this.Bt = GetTemplateChild("PART_BT") as Button;
            this.TvCsv.SelectedItemChanged += TvCsv_SelectedItemChanged;
            this.Bt.Click += Bt_Click;
            Refresh();
        }


        private void Refresh()
        {
            if (TvCsv != null && !string.IsNullOrEmpty(DirPath))
            {
                bool isExists = Directory.Exists(DirPath);
                if (isExists)
                {
                    this.ListNode = new List<Node>();
                    this.AddNode(this.ListNode, this.DirPath);
                    this.TvCsv.ItemsSource = this.ListNode;
                }
            }
        }

        private void Bt_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button Bt)
            {
                txtPageSourceCopy = txtPageSource.Where(s => s.Contains(QueryStr));
                TxtPage.Source = txtPageSourceCopy;
            }
        }

        private void TvCsv_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (GridShow != null)
            {
                try
                {
                    string filePath = DirPath;
                    GetPath(ref filePath, e.NewValue as Node);
                    bool isExists = File.Exists(filePath);
                    string exten = new FileInfo(filePath).Extension;
                    if (isExists)
                    {
                        if (new string[] { ".csv", ".xls", ".xlsx" }.Contains(exten))
                        {
                            DataGrid dataGrid = new DataGrid
                            {
                                MaxColumnWidth = 250d,
                                AutoGenerateColumns = true,
                                IsReadOnly = true,
                                MinRowHeight = 20d,
                                HorizontalContentAlignment = HorizontalAlignment.Center,
                                VerticalContentAlignment = VerticalAlignment.Center
                            };
                            DataTable dt = new DataTable();
                            switch (exten)
                            {
                                case ".csv":
                                    dt = GenCode.CsvContainer.ReadCsv(filePath);
                                    break;
                                case ".xls":
                                case ".xlsx":
                                    using (var stream = File.OpenRead(filePath))
                                    {
                                        dt = stream.QueryAsDataTable();
                                    }
                                    break;
                                default:
                                    break;
                            }
                            ExcelPage excelPage = new ExcelPage();
                            excelPage.Source = dt;
                            GridShow.Children.Clear();
                            GridShow.Children.Add(excelPage);
                        }
                        else
                        {
                            ScrollViewer scrollViewer = new ScrollViewer();
                            scrollViewer.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
                            txtPageSource = File.ReadLines(filePath);
                            TxtPage.Source = txtPageSource;
                            GridShow.Children.Clear();
                            GridShow.Children.Add(TxtPage);
                        }
                    }
                }
                catch (System.Exception)
                {
                }
            }
        }
        private static void OnDirPathChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is DataGridFile DgCsv && DgCsv?.TvCsv != null)
            {
                bool isExists = Directory.Exists(e.NewValue.ToString());
                if (isExists)
                {
                    try
                    {
                        DgCsv.ListNode = new List<Node>();
                        DgCsv.AddNode(DgCsv.ListNode, DgCsv.DirPath);
                        DgCsv.TvCsv.ItemsSource = DgCsv.ListNode;
                    }
                    catch (System.Exception)
                    {
                    }
                }
            }
        }
        private void AddNode(ICollection<Node> nodes, string path, Node Pnode = null)
        {
            try
            {
                var filesX = new DirectoryInfo(path).GetFiles();
                var files = filesX.Where(s => ((string.IsNullOrEmpty(Pattern)) || (Pattern.Split('|')).Contains(s.Extension.ToLower())));

                foreach (var file in files)
                {
                    nodes.Add(new Node(file.Name, Pnode));
                }
                foreach (var item in new DirectoryInfo(path).GetDirectories())
                {
                    Node node = new Node(item.Name, Pnode);
                    AddNode(node.Children, item.FullName, node);
                    nodes.Add(node);
                }
            }
            catch
            {
            }
        }
        private void GetPath(ref string path, Node node)
        {
            if (node.ParentNode == null)
            {
                path += "\\";
                path += node.Name;
            }
            else
            {
                GetPath(ref path, node.ParentNode);
                path += "\\";
                path += node.Name;
            }
        }
    }
}
